<?php
/**
 * This file is part of Hyperf Mall.
 *
 * @link     https://gitee.com/scwlkj/hypref_mall
 * contact  hyperf_mall@163.com
 */
namespace App\JsonRpc;

use App\Cache\TokenCache;
use App\Exception\BaseException;
use App\Repository\AuthRepository;
use App\Repository\Member\MemberRepository;
use App\Repository\MemberOpenIdRepository;
use App\Utils\Log;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\DecryptException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use Hyperf\RpcServer\Annotation\RpcService;
use App\JsonRpc\Interfaces\MemberOpenIdServiceInterface;


/**
 * @RpcService(name="Member::MemberOpenIdService", protocol="jsonrpc", server="jsonrpc")
 */
class MemberOpenIdService extends BaseService implements MemberOpenIdServiceInterface
{

    public function init()
    {
        $this->repository = MemberOpenIdRepository::getInstance();
    }

    /**
     * Notes:
     * Author: Bruce.z
     * DateTime: 2022/7/29 18:24
     * @param string $code
     * @param string $image
     * @param string $username
     * @return array
     * @throws BaseException
     * @throws InvalidConfigException
     */
    public function getOpenId(string $code, string $image, string $username): array
    {
        $config = config('wechat');
        $app = Factory::miniProgram($config['wechat']);

        $session = $app->auth->session($code);
        if(isset($session['errcode']) && isset($session['errmsg'])){
            throw new BaseException(BaseException::BASE_ERROR, $session['errmsg']);
        }

        $row = $this->repository->getOne(['open_id'=>$session['openid']],['member_id']);

        if(empty($row)){
            $row = $this->repository->register($session['openid'], $image, $username);
        }else{
            $row = MemberRepository::getInstance()->getOne(['id'=>$row['member_id']]);
        }

        return AuthRepository::getInstance()->getUserToken($row, TokenCache::TYPE_APP);
    }
}
